import { defineStore } from "pinia";
import { useRouter } from "vue-router/composables";
import {
  addData,
  editData,
  deleteData,
  getTableBody,
  getRoleToAuth,
  getRoleAuthList,
  getAuth,
  insertTreeList,
  roleColumnAuth1,
  roleColumnAuth2,
  roleColumnAuth3,
} from "@/services/roleManage.service";
import { message, Modal } from "ant-design-vue";
import { cloneDeep } from "lodash";
import { getQueryStringData } from "@/utils/tool.js";
import moment from "moment";
export const roleManage = defineStore("role-manage", {
  state: () => {
    return {
      searchData: {
        roleCode: "",
      },
      searchList: [
        {
          view: "text",
          key: "roleCode",
          title: "角色名称",
        },
      ], //查询条件
      formKey: [
        {
          view: "text",
          key: "roleCode",
          title: "角色名称",
        },
        {
          view: "cat_tree",
          key: "topRole",
          title: "上级角色",
        },
        {
          view: "cat_tree_auth",
          key: "permissionIds",
          title: "功能权限",
        },
        {
          view: "text",
          key: "createBy",
          title: "创建人",
        },
        {
          view: "datetime",
          key: "createTime",
          title: "更新时间",
        },
      ], //表单item
      formData: {}, //表单回显
      columns: [
        {
          title: "ID",
          dataIndex: "id",
          align: "center",
          fixed: "left",
          ellipsis: true,
          width: 200,
        },
        {
          title: "角色名称",
          dataIndex: "roleCode",
          align: "center",
          ellipsis: true,
        },
        {
          title: "上级角色",
          dataIndex: "topRole",
          align: "center",
          ellipsis: true,
          scopedSlots: { customRender: "topRole" },
        },
        {
          title: "创建人",
          dataIndex: "createBy",
          align: "center",
          ellipsis: true,
          width: 120,
        },
        {
          title: "更新时间",
          dataIndex: "createTime",
          align: "center",
          ellipsis: true,
        },
        {
          title: "操作",
          dataIndex: "operate",
          align: "center",
          fixed: "right",
          scopedSlots: { customRender: "operate" },
        },
      ],
      tableData: [],
      option: [],
      deleteId: [], //批量删除选中项
      id: getQueryStringData("id"),
      userId: decodeURIComponent(getQueryStringData("userId")),
      pageNo: 1,
      pageSize: 15,
      total: 0,
      dimCode: "",
      visible: false,
      visiblePreview: false,
      disable: false,
      title: "查看-维度管理单",
      tableName: "",
      editNameBack: "", //编辑备份名称
      routerAuthList: [], //功能权限页面
      addBackRoleCode: "",
      allSelectList: [],
    };
  },
  getters: {},
  actions: {
    async reSet() {
      this.searchData = {
        roleCode: "",
      };
      if (this.pageNo === 1) {
        await this.getTbodyData();
      } else {
        this.pageNo = 1;
      }
    },
    //获取功能权限页面list
    getRouterList() {
      const router = useRouter();
      this.routerAuthList = router.options.routes.slice(1).map((item) => {
        this.allSelectList.push({
          label: item.meta.title,
          value: item.name,
        });
        return {
          title: item.meta.title,
          key: item.name,
          value: item.name,
        };
      });
      this.allSelectList.push({
        title: "指标知识图谱",
        value: "indexMapManagement",
      });
      this.routerAuthList.push({
        title: "指标知识图谱",
        key: "indexMapManagement",
        value: "indexMapManagement",
      });
    },

    //新增保存
    async addDataObj() {
      const res = await addData({
        ...this.formData,
        topRole: JSON.stringify(this.formData.topRole),
        permissionIds: JSON.stringify(this.formData.permissionIds),
      });
      if (res.code === 200) {
        this.addBackRoleCode = {
          roleCode: this.formData.roleCode,
          permissionIds: JSON.stringify(this.formData.permissionIds),
        };
        message.success(res.message, 2);
      } else {
        message.error((res && res?.message) || "新增失败", 2);
      }
      return (res && res?.code) || 400;
    },
    //编辑报存
    async editDataObj() {
      const res = await editData({
        ...this.formData,
        topRole: JSON.stringify(this.formData.topRole),
        permissionIds: JSON.stringify(this.formData.permissionIds),
      });
      //角色授权
      const res1 = await insertTreeList({
        roleId: this.formData.id,
        data: JSON.stringify(this.formData.permissionIds),
        opt: "edit",
      });
      await roleColumnAuth1(this.formData.id);
      await roleColumnAuth2(this.formData.id);
      await roleColumnAuth3(this.formData.id);
      await getRoleToAuth(this.formData.id);
      if (res.code === 200 && res1.code === 200) {
        message.success(res.result, 2);
      } else {
        message.error((res && res?.result) || "编辑失败", 2);
      }
      return (res && res?.code) || 400;
    },
    async submit() {
      if (this.title.includes("修改")) {
        await this.editDataObj().then(async (code) => {
          if (code === 200 || code === 0) {
            await this.offModal();
            await this.getTbodyData();
          }
        });
      } else {
        await this.addDataObj().then(async (code) => {
          if (code === 200 || code === 0) {
            await this.offModal();
            await this.getTbodyData(true);
          }
        });
      }
    },
    //新增操作
    addDataOperation(title) {
      let obj = {};
      this.formKey.forEach((item) => {
        if (item.view === "sel_search") {
          obj[item.key] = undefined;
        } else if (item.view === "cat_tree" || item.view === "cat_tree_auth") {
          obj[item.key] = null;
        } else {
          obj[item.key] = "";
        }
      });
      if ("createBy" in obj) {
        obj["createBy"] = this.userId;
      }
      if ("createTime" in obj) {
        obj["createTime"] = moment().format("YYYY-MM-DD HH:mm:ss");
      }

      this.formData = { ...obj };
      this.visible = true;
      this.disable = false;
      this.title = title;
    },
    offModal() {
      let obj = {};
      this.formKey.forEach((item) => {
        if (item.view === "sel_search") {
          obj[item.key] = undefined;
        } else if (item.view === "date") {
          obj[item.key] = null;
        } else if (item.view === "cat_tree" || item.view === "cat_tree_auth") {
          obj[item.key] = null;
        } else {
          obj[item.key] = "";
        }
      });
      this.formData = { ...obj };
      this.visible = false;
    },
    findTitleObj(key, arr) {
      for (let item of arr) {
        if (item.key === key) {
          return [{ label: item.title, value: item.key }];
        }
        if (item.children) {
          let result = this.findTitleObj(key, item.children);
          if (result.length > 0) {
            return result;
          }
        }
      }
      return [];
    },
    //编辑操作
    async editDataOperation(record, type, title, status) {
      let obj = cloneDeep(record);

      if ("createBy" in obj && status) {
        obj["createBy"] = this.userId;
      }
      if ("topRole" in obj) {
        obj["topRole"] = JSON.parse(obj["topRole"]);
      }
      if ("createTime" in obj) {
        obj["createTime"] = moment().format("YYYY-MM-DD HH:mm:ss");
      }
      await getAuth({
        roleId: record.id,
      }).then((res) => {
        if (res.code === 200) {
          obj.permissionIds =
            (res?.result?.length > 0 && JSON.parse(res.result[0])) || [];
        } else {
          obj.permissionIds = [];
        }
      });
      this.formData = { ...obj };
      this.visible = true;
      this.disable = type ? true : false;
      this.editNameBack = record[this.formKey[0].key];
      this.title = title;
    },
    async previewDataOperation(record, type, title, status) {
      let obj = cloneDeep(record);
      if ("topRole" in obj) {
        obj["topRole"] = JSON.parse(obj["topRole"]);
      }
      await getAuth({
        roleId: record.id,
      }).then((res) => {
        if (res.code === 200) {
          obj.permissionIds =
            (res?.result?.length > 0 && JSON.parse(res.result[0])) || [];
        } else {
          obj.permissionIds = [];
        }
      });
      this.formData = { ...obj };
      this.visiblePreview = true;
      this.disable = type ? true : false;
      this.editNameBack = record[this.formKey[0].key];
      this.title = title;
    },
    //删除
    async deleteDataObj(record, type) {
      let that = this;
      if (!type && this.deleteId.length === 0) {
        return Modal.info({
          title: "提示",
          content: "至少选择一条数据",
          centered: true,
        });
      }
      Modal.confirm({
        title: "提示",
        content: "确定删除选中数据吗",
        okText: "确定",
        cancelText: "取消",
        centered: true,
        onOk() {
          return new Promise((resolve, reject) => {
            insertTreeList({
              roleId: type ? record.id : that.deleteId.join(","),
              data: JSON.stringify(""),
              opt: "delete",
            }).then((res1) => {
              if (res1 && res1.code === 200) {
                deleteData({
                  id: type ? "delete" : "deleteBatch",
                  deleteId: type ? record.id : that.deleteId.join(","),
                }).then(async (res) => {
                  if (res.code === 200) {
                    //关闭弹窗
                    resolve();
                    that.getTbodyData();
                    message.success(res.result, 2);
                  } else {
                    //不关闭弹窗
                    reject();
                    message.error(res.result || "指标分类删除失败", 2);
                  }
                });
              } else {
                //不关闭弹窗
                reject();
                message.error("删除失败", 2);
              }
            });
          });
        },
        onCancel() {},
      });
    },
    async getTbodyData(status) {
      let params = cloneDeep(this.searchData);
      for (let key in params) {
        if (!params[key] || params[key].length === 0) {
          delete params[key];
        }
      }
      const res = await getTableBody({
        column: "createTime",
        order: "desc",
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        ...params,
      });
      if (res.code === 0) {
        this.total = res.result.total - 1 || 0;
        this.tableData =
          res.result?.records.filter(
            (item) => item.roleCode !== "jeecg_admin"
          ) || [];
        if (status) {
          let id =
            res.result.records.find(
              (item) => item.roleCode === this.addBackRoleCode.roleCode
            )?.id || "";
          if (id) {
            await insertTreeList({
              roleId: id,
              data: this.addBackRoleCode.permissionIds,
              opt: "add",
            });
            await roleColumnAuth1(id);
            await roleColumnAuth2(id);
            await roleColumnAuth3(id);
            await getRoleToAuth(id);
          }
        }
      } else {
        this.total = 0;
        this.tableData = [];
      }
    },
    //查询
    async search() {
      this.deleteId = [];
      if (this.pageNo === 1) {
        await this.getTbodyData();
      } else {
        this.pageNo = 1;
      }
    },
    updateSearchData(key, value) {
      this.searchData[key] = value;
      this.searchData = { ...this.searchData };
    },
    updateFormData(key, value) {
      this.formData[key] = value;
      this.formData = { ...this.formData };
    },
    updateDeleteId(selectArr) {
      this.deleteId = selectArr;
    },
  },
});
